//
//  MCMarketingDetailViewController.swift
//  StoreManage
//
//  Created by MC on 2018/6/27.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCMarketingDetailViewController: MCViewController {
    
    public var activityId = 0
    
    
    private var dataDict = NSDictionary()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() {
        footerView.closure = { vc  in
            vc.closure = { model in
                self.footerView.model = model
            }
            
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        }
    }
    // MARK: - Action
    @objc func rightItemClicked() {
        
        let vc = MCNewMarketingViewController()
        vc.activityId = activityId
        vc.dataDict = dataDict
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    
    
    @objc func releaseButtonClicked() {
        
        
        MCHUD_default(message: "加载中", view: self.view, delay: 0)
        
        let para = [
            "activityId" : activityId,
            "communityId" : self.footerView.model.communityId.intValue
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_addLaunchDistribution, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
          
            MCHUD_hidden(view: self.view)
            
            let data = response["data"] as? NSNumber ?? 0
       
            let vc = MCReleaseMarketingViewController()
            vc.activityLogId = data.intValue
            vc.dataDict = self.dataDict
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            
        }, dislike: { (response) in
            MCHUD_hidden(view: self.view)
        }) { (error) in
            MCHUD_hidden(view: self.view)
        }
        
        
        
    }
    // MARK: - Network
    func sendNetworking() {
        sendNetworking_detail()
    }
    
    func sendNetworking_detail() {
        let para = [
            "activityId" : activityId,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_findActivityDetailById, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as? [String : AnyObject] ?? [:]

            self.dataDict = dataDict as NSDictionary
            
            let activityStatus = dataDict["activityStatus"] as? NSNumber ?? 0
            let status = dataDict["status"] as? NSNumber ?? 0
            
            
            let title = dataDict["title"] as? String ?? ""
            let remark = dataDict["remark"] as? String ?? ""
            let createTime = dataDict["createTime"] as? String ?? ""
            
            let startTime = dataDict["startTime"] as? String ?? ""
            let endTime = dataDict["endTime"] as? String ?? ""
            let pickUpStartTime = dataDict["pickUpStartTime"] as? String ?? ""
            let pickUpEndTime = dataDict["pickUpEndTime"] as? String ?? ""
            let goodsList = dataDict["goodsList"] as? NSArray ?? NSArray()
            
            
            self.headerView.titleLabel.text = title
            self.title = title
            
            self.headerView.detailLabel.text = remark
            self.headerView.timeLabel.text = createTime
            self.headerView.activityTimeLabel.text = "活动时间:" + startTime.MCString_prefix(index: 10)  + " ~ " + endTime.MCString_prefix(index: 10)
            self.headerView.pickUpTimeLabel.text = "提货时间:" + pickUpStartTime.MCString_prefix(index: 10)  + " ~ " + pickUpEndTime.MCString_prefix(index: 10)
            

            
            
            self.sendNetworking_communityList(status: status.intValue, activityStatus: activityStatus.intValue)

            
            
            for dict in goodsList {
                let model = MCResueGoodsModel()
                model.setValuesForKeys(dict as? [String:Any] ?? [:])
                self.dataArrayM.add(model)
            }
            self.tableView.reloadData()
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    func sendNetworking_communityList(status:Int,activityStatus:Int) {
        let para = [
            "clerkId" : MCUserinfo_getUserId(),
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_findCommunityListByUserId, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataArray = response["data"] as? NSArray ?? []
          
            let model = MCCommunityModel()
            
            
            
            if status == 0 {  // 活动被禁用
                self.releaseButton.setTitle("活动被禁用", for:.normal)
                self.releaseButton.isSelected = false
                self.releaseButton.isEnabled = false
            } else {
                if activityStatus == 0 { // 0进行中
                    if dataArray.count == 0 {  // 没有配送社区，请联系店长
                        self.releaseButton.setTitle("没有配送社区，请联系店长", for:.normal)
                        self.releaseButton.isSelected = false
                        self.releaseButton.isEnabled = false
                    } else {
                        
                        model.setValuesForKeys(dataArray[0] as? [String:Any] ?? [:])
                        self.releaseButton.setTitle("发起分销", for:.normal)
                        self.releaseButton.isSelected = true
                        self.releaseButton.isEnabled = true
                    }
                } else if activityStatus == 1 {  // 1已完成
                    self.releaseButton.setTitle("分销结束", for:.normal)
                    self.releaseButton.isSelected = false
                    self.releaseButton.isEnabled = false
                } else {  // 2未开始
                    self.releaseButton.setTitle("分销未开始", for:.normal)
                    self.releaseButton.isSelected = false
                    self.releaseButton.isEnabled = false
                }
            }


            
            self.footerView.model = model
            
        }, dislike: { (response) in }) { (error) in }

    }
    
    // MARK: - Method
    func baseSetting() {
        self.view.backgroundColor = UIColor.white
        
        if MCUserinfo_getLevel() == MCRole_manager {
            
            navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("编辑", target: self, selector: #selector(rightItemClicked))
        }
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 50, 0))
        }
        
        view.addSubview(releaseButton)
        releaseButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(50)
        }
        
        tableView.tableHeaderView = headerView
        tableView.tableFooterView = footerView
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var releaseButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitleColor(UIColor.white, for: .normal)
        
        button.setBackgroundImage(UIImage.init(color: UIColor.MCGray_middle), for: .normal)

        button.setBackgroundImage(UIImage.init(color: UIColor.MCMain), for: .selected)


        button.isEnabled = false
        
        
        button.addTarget(self, action: #selector(releaseButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var headerView: MCMarketingDetailHeaderView = {
        let view = MCMarketingDetailHeaderView()
        return view
    }()
    
    lazy var footerView: MCMarketingDetailFooterView = {
        let view = MCMarketingDetailFooterView()
        return view
    }()
}

extension MCMarketingDetailViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 105
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCMarketingDetailCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.MCGray_light
        cell.model = self.dataArrayM[indexPath.row] as! MCResueGoodsModel
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = MCGoodsDetailViewController()
    
        let model = self.dataArrayM[indexPath.row] as! MCResueGoodsModel
        vc.isOnShelves = 1
        vc.goodsId = (model.goodsId?.intValue)!
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}

